#include "singlestepcontrol.h"

SingleStepControl::SingleStepControl(QWidget *parent) : QWidget(parent)
{

}

SingleStepControl::SingleStepControl(const QString &Name, const QJsonObject &functionDetails, QWidget *parent)
    : QWidget(parent)
{
    QGroupBox *groupBox = new QGroupBox("单步控制", this);
    groupBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    createSingleStepControl(groupBox, functionDetails);

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(groupBox);
    layout->setContentsMargins(0, 0, 0, 0);
    qDebug() << "测试是否进入单步控制";

    setLayout(layout);
}

void SingleStepControl::createSingleStepControl(QGroupBox *groupBox, const QJsonObject &functionDetails)
{
    qDebug() << "functionDetails :" << functionDetails;
    QVBoxLayout *mainLayout = new QVBoxLayout();
    groupBox->setLayout(mainLayout);
    QJsonObject Details = functionDetails["Parameters"].toObject();

    // 创建用于放置按钮的窗口
    QWidget *PushButtonWidget = new QWidget(groupBox);
    QHBoxLayout *PushButtonLayout = new QHBoxLayout(PushButtonWidget);
    PushButtonWidget->setLayout(PushButtonLayout);
    PushButtonWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    QJsonArray pushbuttonArray = Details["pushbutton"].toArray();
    qDebug() << "Pushbutton Array:" << pushbuttonArray;

    // 遍历 pushbuttonArray，为每个按钮连接同一个槽函数
    for (int i = 0; i < pushbuttonArray.size(); ++i) {
    QString buttonText = pushbuttonArray[i].toString();
    QPushButton *button = new QPushButton(buttonText, PushButtonWidget);
    button->setMaximumSize(200, 60);
    PushButtonLayout->addWidget(button);

    connect(button, &QPushButton::clicked, this, &SingleStepControl::onButtonClicked);
    }
    mainLayout->addWidget(PushButtonWidget);
}

void SingleStepControl::onButtonClicked()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
       if (!button)
           return;

       QString buttonText = button->text();
       qDebug() << "Button clicked:" << buttonText;

       // 根据按钮的文本执行不同的逻辑
       if (buttonText == "moveCW") {
           qDebug() << "moveCW logic executed";
           // 添加 moveCCW 的逻辑代码
       } else if (buttonText == "moveCCW") {
           qDebug() << "moveCCW logic executed";
           // 添加 moveCCW 的逻辑代码
       } else if (buttonText == "stopSingleStep") {
           qDebug() << "stopSingleStep logic executed";
           // 添加 stopSingleStep 的逻辑代码
       } else {
           qDebug() << "Unknown button clicked:" << buttonText;
       }
}
